package park.job;

import net.sf.json.JSONObject;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import park.log.Chart;
//
//<<<<<<< HEAD
//import com.google.gson.Gson;
//
//import net.sf.json.JSONObject;
//import park.record.EntryRecord;
//
//public class ParkInterfaceCollection {
//
//	private static RequestConfig build;
//	private static CloseableHttpClient httpClient;
//	private Logger log = Logger.getLogger(ParkInterfaceCollection.class.getName());
//
//	private static ParkInterfaceCollection instance = null;
//
//	public static ParkInterfaceCollection getInstance() {
//		if (instance == null) {
//			instance = new ParkInterfaceCollection();
//		}
//		return instance;
//
//	}
//
//	private ParkInterfaceCollection() {
//		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
//		cm.setMaxTotal(300);
//		cm.setDefaultMaxPerRoute(300);
//		//cm.setDefaultMaxPerRoute(300);
//		httpClient = HttpClients.custom().setConnectionManager(cm).build();
//		build = RequestConfig.custom().setConnectTimeout(6000).setConnectionRequestTimeout(2000).setSocketTimeout(8000)
//				.build();
//
//	}
//
//	public CloseableHttpClient getHttpclient() {
//		return httpClient;
//	}
//
//	public RequestConfig getBuild() {
//		return build;
//	}
//
//
//	public <T> String postFunc(String url,T t) throws ClientProtocolException, IOException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException{
//	
//		HttpPost httppost = new HttpPost("http://192.168.11.146:8000/innerParkMaintenanceService/"+url);
//		httppost.setConfig(build);
//		JSONObject jsonParam = convertClazz( t);
//		jsonParam.put("invokeSerial", UUID.randomUUID());
//
//		
//		StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");// 解决中文乱码问题
//		entity.setContentEncoding("UTF-8");
//		entity.setContentType("application/json");
//		httppost.setEntity(entity);
//		long current = System.currentTimeMillis();
//		Date before = new Date(System.currentTimeMillis());
//		log.info("Executing request: " + httppost.getRequestLine()+" time:"+before);
//		
//		CloseableHttpResponse response = httpClient.execute(httppost);
//		log.info("reponse request of: " + url+", spend time:"+(System.currentTimeMillis()-current)+"ms");
//		CloseableHttpResponse returnRes = response;
//		String re; 
//		try {
//			System.out.println("----------------------------------------");
//			System.out.println(response.getStatusLine());
//			 re = EntityUtils.toString(response.getEntity());
//			System.out.println(re);
//		} finally {
//			response.close();
//		}
//		return re;
//		
//	}
//
//	public <T> JSONObject convertClazz(T clazz) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
//		JSONObject jsonParam = new JSONObject();
//		Field[] fields = clazz.getClass().getFields();
//
//		// clazz.getMethod(name, parameterTypes)
//		//T obj = clazz.newInstance();
//		for (Field field : fields) {
//			String fieldName = field.getName();
//			String firstLetter = fieldName.substring(0, 1).toUpperCase(); // 获得和属性对应的getXXX()方法的名字
//			String getMethodName = "get" + firstLetter + fieldName.substring(1); // 获得和属性对应的getXXX()方法的名字
//			Method getMethod = clazz.getClass().getMethod(getMethodName, new Class[] {}); // 获得和属性对应的getXXX()方法
//			Object value = getMethod.invoke(clazz, new Object[] {});
//			jsonParam.put(fieldName, value);
//		}
//		return jsonParam;
//
//	}

	

		

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

public class ParkInterfaceCollection
{
    private static ConcurrentHashMap<String,String> recordMap;
    private static RequestConfig build;
    private static CloseableHttpClient httpClient;
    private static ParkInterfaceCollection instance = null;
    private Logger log = Logger.getLogger(ParkInterfaceCollection.class.getName());
   
    public static ConcurrentHashMap<String, String> getRecordMap() {
		return recordMap;
	}


	public static void setRecordMap(ConcurrentHashMap<String, String> recordMap) {
		ParkInterfaceCollection.recordMap = recordMap;
	}
	public static void clearMap() {
		recordMap.clear();
	}

	private ParkInterfaceCollection()
    {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(300);
        cm.setDefaultMaxPerRoute(300);
        //cm.setDefaultMaxPerRoute(300);
        httpClient = HttpClients.custom().setConnectionManager(cm).build();
        build = RequestConfig.custom().setConnectTimeout(6000).setConnectionRequestTimeout(2000).setSocketTimeout(8000)
                .build();
        recordMap = new ConcurrentHashMap<String,String>();
    }


    public static ParkInterfaceCollection getInstance()
    {
        if (instance == null)
        {
            instance = new ParkInterfaceCollection();
        }
        return instance;
    }

    public CloseableHttpClient getHttpclient()
    {
        return httpClient;
    }

    public RequestConfig getBuild()
    {
        return build;
    }

    public <T> String postFunc(
            String url,
            T t) throws ClientProtocolException, IOException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException
    {

        long timeMark = System.currentTimeMillis();
        HttpPost httppost = new HttpPost("http://192.168.11.146:8000/innerParkMaintenanceService/" + url);
        httppost.setConfig(build);
        JSONObject jsonParam = convertClazz(t);
        jsonParam.put("invokeSerial", UUID.randomUUID());

        StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");// 解决中文乱码问题
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httppost.setEntity(entity);
        long current = System.currentTimeMillis();
        Date before = new Date(System.currentTimeMillis());
        log.info("Executing request: " + httppost.getRequestLine() + " time:" + before);

        CloseableHttpResponse response = httpClient.execute(httppost);
        log.info("reponse request of: " + url + ", spend time:" + (System.currentTimeMillis() - current) + "ms");
        CloseableHttpResponse returnRes = response;
        String re;
        try
        {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            re = EntityUtils.toString(response.getEntity());
            System.out.println(re);
        }
        finally
        {
            response.close();
        }
        //
    //    Chart.remember(url, System.currentTimeMillis() - timeMark);
        recordMap.put(new Date(timeMark).toString(), url+"_"+String.valueOf(System.currentTimeMillis() - timeMark));
        log.info(url+": map size is:"+recordMap.size());
        
        return re;
    }

    public <T> JSONObject convertClazz(
            T clazz) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException
    {
        JSONObject jsonParam = new JSONObject();
        Field[] fields = clazz.getClass().getFields();

        // clazz.getMethod(name, parameterTypes)
        //T obj = clazz.newInstance();
        for (Field field : fields)
        {
            String fieldName = field.getName();
            String firstLetter = fieldName.substring(0, 1).toUpperCase(); // 获得和属性对应的getXXX()方法的名字
            String getMethodName = "get" + firstLetter + fieldName.substring(1); // 获得和属性对应的getXXX()方法的名字
            Method getMethod = clazz.getClass().getMethod(getMethodName, new Class[]{}); // 获得和属性对应的getXXX()方法
            Object value = getMethod.invoke(clazz, new Object[]{});
            jsonParam.put(fieldName, value);
        }
        return jsonParam;
    }
}
